import React, { useState, useEffect } from 'react';
import {
  Button,
  Card,
  Form,
  Input,
  Modal,
  Space,
  Table,
  message,
  DatePicker,
  ConfigProvider,
  Popconfirm,
} from 'antd';
import {
  PlusOutlined,
  SearchOutlined,
  EditOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
import {
  HonorInfo,
  getHonorPage,
  addHonor,
  updateHonor,
  deleteHonor,
} from '@/services/HonorService';
import styles from './index.less';
import { famousPersonId } from '@/services';
import dayjs from 'dayjs';
import locale from 'antd/locale/zh_CN';

const { TextArea } = Input;
const { RangePicker } = DatePicker;

const HonorAdmin: React.FC = () => {
  const [searchForm] = Form.useForm();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<HonorInfo[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingId, setEditingId] = useState<number | undefined>();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
  });

  // 加载数据
  const loadData = async (page = pagination.current, pageSize = pagination.pageSize) => {
    try {
      setLoading(true);
      const values = await searchForm.validateFields();
      const response = await getHonorPage({
        pageCurrent: page,
        pageSize: pageSize,
        famousPersonId: famousPersonId,
        keyword: values.keyword,
        startDate: values.dateRange?.[0]?.format('YYYY-MM-DD'),
        endDate: values.dateRange?.[1]?.format('YYYY-MM-DD'),
      });
      setData(response.list);
      setPagination({
        current: page,
        pageSize: pageSize,
        total: response.totalCount,
      });
    } catch (error) {
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理删除
  const handleDelete = async (id: number) => {
    try {
      await deleteHonor([id]);
      message.success('删除成功');
      loadData();
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 处理取消
  const handleCancel = () => {
    setModalVisible(false);
    setEditingId(undefined);
    form.resetFields();
  };


  // 处理表单提交
  const handleSubmit = async (values: any) => {
    try {
      const submitData = {
        ...values,
        famousPersonId,
        // 转换为 YYYY-MM-DD 格式的字符串
        awardDate: values.awardDate?.format('YYYY-MM-DD'),
      };

      if (editingId) {
        await updateHonor({ ...submitData, id: editingId });
        message.success('更新成功');
      } else {
        await addHonor(submitData);
        message.success('添加成功');
      }
      handleCancel();
      loadData();
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 处理编辑
  const handleEdit = (record: HonorInfo) => {
    setEditingId(record.id);
    form.setFieldsValue({
      ...record,
      // 处理时间戳转换为 dayjs 对象
      awardDate: record.awardDate
        ? dayjs(typeof record.awardDate === 'number'
          ? record.awardDate
          : record.awardDate
        )
        : undefined,
    });
    setModalVisible(true);
  };

  useEffect(() => {
    loadData();
  }, []);

  // 列定义
  const columns = [
    {
      title: '荣誉名称',
      dataIndex: 'name',
      key: 'name',
      width: '25%',
    },
    {
      title: '获奖日期',
      dataIndex: 'awardDate',
      key: 'awardDate',
      width: '15%',
      render: (date: string | number) => {
        if (!date) return '-';
        // 处理时间戳
        return typeof date === 'number'
          ? dayjs(date).format('YYYY-MM-DD')
          : dayjs(date).format('YYYY-MM-DD');
      },
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      width: '40%',
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'action',
      width: '20%',
      render: (_: any, record: HonorInfo) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个荣誉吗？"
            onConfirm={() => handleDelete(record.id!)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 渲染搜索表单
  const renderSearchForm = () => (
    <Form
      form={searchForm}
      layout="inline"
      onFinish={() => loadData(1)}
      initialValues={{
        status: '',
      }}
    >
      <Form.Item name="keyword">
        <Input
          placeholder="请输入荣誉名称或描述"
          allowClear
          prefix={<SearchOutlined />}
        />
      </Form.Item>
      <Form.Item name="dateRange">
        <RangePicker />
      </Form.Item>
      <Form.Item>
        <Space>
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
          <Button onClick={() => {
            searchForm.resetFields();
            loadData(1, 20);
          }}>
            重置
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );

  return (
    <ConfigProvider locale={locale}>
      <Card title="荣誉奖项管理">
        <div className={styles.toolbar}>
          {renderSearchForm()}
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => setModalVisible(true)}
          >
            新增荣誉
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
          scroll={{ y: 'calc(100vh - 410px)', scrollToFirstRowOnChange: false }}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            pageSizeOptions: ['20', '50', '100'],
          }}
          onChange={(newPagination) => {
            loadData(newPagination.current, newPagination.pageSize);
          }}
        />

        <Modal
          title={editingId ? '编辑荣誉' : '新增荣誉'}
          open={modalVisible}
          onCancel={handleCancel}
          footer={null}
          width={600}
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
          >
            <Form.Item
              name="name"
              label="荣誉名称"
              rules={[{ required: true, message: '请输入荣誉名称' }]}
            >
              <Input placeholder="请输入荣誉名称" maxLength={255} />
            </Form.Item>

            <Form.Item
              name="awardDate"
              label="获奖日期"
            >
              <DatePicker
                style={{ width: '100%' }}
                placeholder="请选择获奖日期（可选）"
              />
            </Form.Item>

            <Form.Item
              name="description"
              label="荣誉描述"
            >
              <TextArea
                rows={4}
                placeholder="请输入荣誉描述（可选）"
                maxLength={1000}
                showCount
              />
            </Form.Item>

            <Form.Item className={styles.modalFooter}>
              <Space>
                <Button onClick={handleCancel}>取消</Button>
                <Button type="primary" htmlType="submit">
                  保存
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </ConfigProvider>
  );
};

export default HonorAdmin; 